<template>
    <div>
        用户列表
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 用户列表主体部分 -->
        <el-card class="el_card">
            <el-row :gutter="25">
                <!-- 搜索区域 -->
                <!-- 搜索添加 -->
                <el-col :span="10">
                    <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="getUserList"
                        ></el-button>
                    </el-input>
                </el-col>
                <!-- 搜索按钮 -->
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true"
                        >添加用户</el-button
                    >
                </el-col>
            </el-row>
        </el-card>

        <!-- 用户列表数据展示区域 border边框  stripe隔行变色 -->
        <el-table :data="userList" border stripe>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
                label="id"
                prop="id"
                v-if="false"
            ></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="密码" prop="password"></el-table-column>
            <el-table-column label="角色" prop="role"></el-table-column>
            <el-table-column label="状态" prop="state">
                <!-- 作用域插槽 -->
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" @change="updateStateChanged(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 修改 -->
                    <el-button
                        type="primary"
                        icon="el-icon-edit"
                        size="mini"
                        @click="showEditDailog(scope.row.id)"
                    ></el-button>
                    <!-- 删除 -->
                    <el-button
                        type="danger"
                        icon="el-icon-delete"
                        size="mini"
                        @click="deleteUser(scope.row.id)"
                    ></el-button>
                    <!-- 权限 -->
                    <el-tooltip
                        effect="dark"
                        content="分配权限"
                        placement="top-start"
                        :enterable="false"
                    >
                        <el-button
                            type="warning"
                            icon="el-icon-setting"
                            size="mini"
                        ></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页组件 size-change每页最大变化数 current-change当前页最大变化 layout功能组件-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum"
            :page-sizes="[1, 2, 5, 100]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>

        <!-- 新增用户区域 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
            </el-form>
            <!-- 内容底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="addUser">确定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>
            <!-- 内容底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="editUser">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    created() {
        this.getUserList();
    },
    data() {
        var addCheckEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
            if (!value) {
                return callback(new Error('邮箱不能为空'));
            }
            setTimeout(() => {
                if (mailReg.test(value)) {
                callback();
                } else {
                callback(new Error('请输入正确的邮箱格式'));
                }
            }, 100)
        };
        var editCheckEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
            if (!value) {
                return callback(new Error('邮箱不能为空'));
            }
            setTimeout(() => {
                if (mailReg.test(value)) {
                callback();
                } else {
                callback(new Error('请输入正确的邮箱格式'));
                }
            }, 100)
        };
        return {
            // 查询实体类
            queryInfo: {
                query: "", // 查询信息
                pageNum: 1, // 当前页
                pageSize: 2, // 每页最大数
            },
            userList: [],
            total: 0, // 总记录数据
            addDialogVisible : false, //对话框状态
            // 添加用户信息
            addForm:{
                username:"",
                password:"",
                email:"",
            },
            // 修改用户信息
            editForm:{
                id:"",
                username:"",
                password:"",
                email:"",
            },
            editDialogVisible : false, //编辑弹窗框状态
            // 表单验证
            // 验证新增表单对象
            addFormRules:{
                // 校验用户名
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' }, // 必填项验证
                    { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' } // 长度验证
                ],
                // 校验密码
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' }, // 必填项验证
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' } // 长度验证
                ],
                // 校验邮箱
                email:[
                    { required: true, message: '请输入正确邮箱地址', trigger: 'blur' }, // 必填项验证
                    { validator: addCheckEmail, message: '请输入正确邮箱地址', trigger: 'blur' } // 邮箱规则验证
                ],
            },
            // 验证编辑表单对象
            editFormRules:{
                // 校验密码
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' }, // 必填项验证
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' } // 长度验证
                ],
                // 校验邮箱
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' }, // 必填项验证
                    { validator: editCheckEmail, message: '请输入正确邮箱地址', trigger: 'blur' } // 邮箱规则验证
                ],
            },
        };
    },
    methods: {
        // 获取所有用户
        async getUserList() {
            const { data: res } = await this.$http.get("/allUser", {
                params: this.queryInfo,
            });
            this.userList = res.data;//用户列表数据封转
            this.total = res.numbers;//总用户数量
        },
        // 最大分页数
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getUserList();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.pageNum = newPage;
            this.getUserList();
        },
        async updateStateChanged(userInfo){
            const {data:res} = await this.$http.put(`userState?id=${userInfo.id}&state=${userInfo.state}`);
            if(res!="success"){
                userInfo.id = !userInfo.id;
                return this.$message.error("操作失败");
            }else{
                return this.$message.success("操作成功");
            }
        },
        // 监听添加用户
        addDialogClosed(){
            this.$refs.addFormRef.resetFields();
        },
        addUser(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid){
                    return;
                }
                const {data:res} = await this.$http.post("/addUser",this.addForm);
                if(res!="success"){
                    this.$message.error("操作失败");
                }
                this.$message.success("操作成功，已发送邮箱，请前往邮箱激活用户");
                this.addDialogVisible = false;
                this.getUserList();
            });
        },
        async deleteUser(id) {
            const confirmResult = await this.$confirm("此操作将永久删除用户，是否继续？",'提示',{
                confirmButtonText:"确认",
                cancelButtonText:"取消",
                type:"warning"
            }).catch(err => err)
            if(confirmResult!="confirm"){
                return this.$message.info("已取消删除");
            }
            const {data:res} = await this.$http.delete("/deleteUser?id="+id);
            if(res!="success"){
                    this.$message.error("删除失败");
            }
            this.$message.success("删除成功");
            this.getUserList();
        },
        // 关闭编辑窗口
        editDialogClosed(){
            this.$refs.editFormRef.resetFields();// 重置信息
        },
        // 显示编辑对话框
        async showEditDailog(id) {
            const {data:res} = await this.$http.get("/getUpdateUser?id="+id);
            // this.editForm = res;
            this.editForm.id = res.id;
            this.editForm.username = res.username;
            this.editForm.password = res.password;
            this.editForm.email = res.email;
            this.editDialogVisible = true;
        },
        async editUser(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid){
                    return;
                }
                const {data:res} = await this.$http.put("editUser", this.editForm);
                if(res!="success"){
                        this.$message.error("保存失败");
                }
                this.$message.success("保存成功");
                this.editDialogVisible = false;
                this.getUserList();
            })
        }
    },
};
</script>
<style lang="less" scoped>
.el-breadcrumb {
    margin-bottom: 15px;
    font-size: 17px;
}
</style>